import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_shop/pages/base/base_presenter.dart';
import 'package:flutter_shop/pages/base/base_state.dart';
import 'package:flutter_shop/widget/common_app_bar.dart';
import 'package:webview_flutter/webview_flutter.dart';

///Title:常规webview页 <br/>
///Description: <br/>
///author:xiemiao <br/>
///date: 2020-02-21 <br/>
///version 1.0 <br/>
class WebViewPage extends StatefulWidget {
  final String title;
  final String url;

  const WebViewPage({Key key, @required this.title, @required this.url}) : super(key: key);

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends BaseState<WebViewPage, BasePresenter> {
  final Completer<WebViewController> _controller = Completer<WebViewController>();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<WebViewController>(
        future: _controller.future,
        builder: (context, snapshot) {
          if (snapshot.hasData && !widget.url.startsWith("http")) {
            _loadRichText(snapshot.data, widget.url);
          }

          return WillPopScope(
            onWillPop: () async {
              if (snapshot.hasData) {
                bool canGoBack = await snapshot.data.canGoBack();
                if (canGoBack) {
                  // 网页可以返回时，优先返回上一页
                  snapshot.data.goBack();
                  return Future.value(false);
                }
                return Future.value(true);
              }
              return Future.value(true);
            },
            child: Scaffold(
                appBar: CommonAppBar(widget.title),
                body: WebView(
                  initialUrl: widget.url,
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webViewController) {
                    _controller.complete(webViewController);
                  },
                )),
          );
        });
  }

  ///加载富文本
  void _loadRichText(WebViewController controller, String richText) async {
    final String contentBase64 = base64Encode(const Utf8Encoder().convert(richText));
    await controller.loadUrl('data:text/html;base64,$contentBase64');
  }
}
